<?php

class Poll_Table_Model_Poll extends Database_Model_Item
{
	protected $_pk = 'poll_id';

	protected $_itemType = 'poll';

	function getTitle()
	{
		return $this -> question;
	}

	function getUrl()
	{
		return Nuo::getUrl('poll/view', array('poll_id' => $this -> getId()));
	}

	protected function _setAnswer($value = NULL)
	{

	}

	/**
	 * get all answer
	 */
	function getAnswers()
	{
		$table = Nuo::getTable('poll/answer');
		$select = $table -> select() -> where('poll_id=?', $this -> getId());
		return $table -> fetchAll($select);
	}

	/**
	 * remove all answer
	 */
	function removeAnswers()
	{
		$table = Nuo::getTable('poll/answer');
		$table -> delete('poll_id=' . $this -> getId());
	}

	/**
	 * @param array
	 */
	function setAnswers($answers)
	{
		$ids = array();

		// delete old poll.
		$this -> removeAnswers();
		$table = Nuo::getTable('poll/answer');

		$sort = 0;
		foreach ($answers as $answer)
		{
			$item = $table -> fetchNew();
			$item -> poll_id = $this -> getId();
			$item -> label = $answer['label'];
			$item -> sort_order = ++$sort;
			$item -> created_at = time();
			$item -> save();

		}
	}

	/**
	 * process vote and some thing else.
	 */
	function vote($userId, $answers)
	{
		$table = Nuo::getTable('poll/vote');

		// delete old vote
		$table -> delete(array(
			'user_id=?' => $userId,
			'poll_id=?' => $this -> getId()
		));

		foreach ($answers as $id)
		{
			$vote = $table -> fetchNew();
			$vote -> poll_id = $this -> getId();
			$vote -> answer_id = (int)$id;
			$vote -> user_id = $userId;
			$vote -> created_at = time();
			$vote -> created_ip = $request->getClientIp();
			$vote -> save();
		}
	}

}
